//-------------------------------------------------------------
// \project pluginpamiss
// \file ModuleGetSqlFromCIMISS.java
// \brief CIMISS转为PAMISS
// \author 张伟
// \date 2017-03-03
// \attention
// Copyright(c) 超图软件股份有限公司 气象事业部
// All Rights Reserved
// \version 1.0
//-------------------------------------------------------------

package com.mg.pluginpamiss;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mg.model.*;
import com.mg.pluginexample2.Model2;
import com.mg.pluginexample2.ModuleBase;

/**
 * 如果输入端或输出端可动态增删端口，需要派生端口类，否则Undo可能出错。
 */

//class VariablePort extends Port
//{
//	public VariablePort(Module module)
//	{
//		super(module);
//    }
//	public VariablePort(Module module, Type eType)
//	{
//		super(module, eType);
//    }
//	public Port Clone()
//	{
//		VariablePort vp = new VariablePort(null, m_eType);
//		vp.m_strName = m_strName;
//		vp.m_strVarName = m_strVarName;
//		vp.m_dVarValue = m_dVarValue;
//		vp.m_rs = m_rs;
//		vp.m_al = m_al;
//		return vp;
//	}
//	
//	String m_strVarName = "";
//	double m_dVarValue = -9999; //支持指定数值
//	ResultSet m_rs = null;
//	ArrayList<String> m_al = null;
//	
//	HashMap<Integer, Integer> m_hm = null; //区站号->行号
//}
public class CimissToPamiss extends ModuleBase//模块
{
	public CimissToPamiss(int nID)
	{
		super(nID);
		
		m_alInputPort.add(new Port(this, Port.Type.Unknown));
		m_alOutputPort.add(new Port(this, Port.Type.Unknown));//输出字符串
		
		m_alExpressionItem = new ArrayList<ExpressionItem>();
		m_alExpressionItem.add(new ExpressionItem());
		
		
    }

	public String GetGroupName()
	{
		return "PAMISS";
	}
	public String GetName()
	{
		return "CIMISS数据-PAMISS";
	}
	public String GetDescription()
	{
		return "";
	}
	
	public boolean OnAttach(Port portFrom, Port portTo)
	{
		try
		{
			int i = FindPort(portFrom, false);
			if (i != -1)
				return true;
			i = FindPort(portTo, true);
			if (i == -1)
				return false;
			if (portFrom.GetType() != portTo.GetType())
				return false;
			ArrayList<Param> alParam = new ArrayList<Param>();
			portFrom.GetModule().GetOutputParam(portFrom, alParam);
			if (alParam.size() < 1)
				return false;
			if (alParam.get(0).m_objValue != null && !(alParam.get(0).m_objValue instanceof List))
				return false;
			if (alParam.get(0).m_objValue instanceof List)
				m_map = (List<Object>)alParam.get(0).m_objValue;
			if(m_alExpressionItem.size()<1)
			{
				if(m_map!=null &&m_map.get(0) instanceof String)
				{
					String[] titles=((String)m_map.get(0)).split(",");
					String[] types=((String)m_map.get(1)).split(",");
					for(i = 0;i<titles.length;i++){
						String strGroups = String.format("取/值条件/第%d个取值条件", i + 1);
						ExpressionItem ei1 = new ExpressionItem();
						//for(j=0;j<i;j++){
						ei1.m_strOldTitle=titles[i];
						ei1.m_strNewTitle=titles[i];
						//}
						m_alExpressionItem.add(ei1);
						}
				}
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return false;
		}
		
		return true;
	}
	public boolean OnDetach(Port portFrom, Port portTo)
	{
		if (!super.OnDetach(portFrom, portTo))
			return false;
		try
		{
			int i = FindPort(portTo, true);
			if (i == -1)
				return true;
			return true;
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return false;
		}
	}
	
	//用于 参数->XML 等
	public int GetParam(ArrayList<Param> alParam)//获得参数
	{
		try
		{
			super.GetParam(alParam);
			//-------------------------------------------------------------------------------------------------------------------
			Model2 model = ((Model2)m_model);
        	String strDatasources = model.GetWritableDatasources(true);
        	String strOptionalValues = "|字符|时间|降水|风向|X10|X100000|系统时间|char3|char4";
        	
        	alParam.add(new Param("ExpressionItemCount", String.format("%d", m_alExpressionItem.size()), "取值条件个数", "", "取值条件", Param.EditType.ItemCount, "2")); //"2":ExpressionItem参数个数
        	if(m_alExpressionItem==null || m_alExpressionItem.size()<1 ){
			
        		m_alExpressionItem.clear();
        		if(m_map!=null &&m_map.get(0) instanceof String)
				{
					String[] titles=((String)m_map.get(0)).split(",");
					String[] types=((String)m_map.get(1)).split(",");
					for(int i = 0;i<titles.length;i++){
						String strGroups = String.format("取/值条件/第%d个取值条件", i + 1);
						ExpressionItem ei1 = new ExpressionItem();
						ei1.m_strOldTitle=titles[i];
						ei1.m_strNewTitle=titles[i];
						m_alExpressionItem.add(ei1);
						}
				}
//        		
//        		String [] strOld={"x","y","value"};
//        		String [] strNew={"x","y","value"};
////        		String [] strCondition={"x","y","value"};
//        		int j =0;
//        		for(int i=1;i<4;i++){	
//        		String strGroups = String.format("取值条件/第%d个取值条件", i);
//        		ExpressionItem ei1 = new ExpressionItem();
//        		alParam.add(new Param("OldTitle", strOld[j], "选择字段", "", strGroups, Param.EditType.Default));  
//				alParam.add(new Param("NewTitle", strNew[j], "目标表字段", "目标字段为要导入的目标表字段，如为空则默认设置为查询结果字段", strGroups, Param.EditType.Default));
//				alParam.add(new Param("Condition",ei1.m_strCondition, "取值条件", "", strGroups, Param.EditType.SelectOrInput,strOptionalValues));
//        		for(j=0;j<i;j++){
//        			ei1.m_strOldTitle = strOld[j];
//        			ei1.m_strNewTitle = strNew[j];
////        			ei1.m_strCondition= strCondition[j];
//    				}
//    				m_alExpressionItem.add(ei1);
//        		}
        	}
        	for (int i = 0; i < m_alExpressionItem.size(); i++)
			{
				ExpressionItem ei = m_alExpressionItem.get(i);
				String strGroups = String.format("取值条件/第%d个取值条件", i + 1);
				//String strGroup  = String.format("取值条件/第%d个取值条件",i +1);
				
				alParam.add(new Param("OldTitle", ei.m_strOldTitle, "选择字段", "", strGroups, Param.EditType.Default));  
				alParam.add(new Param("NewTitle", ei.m_strNewTitle, "目标表字段", "目标字段为要导入的目标表字段，如为空则默认设置为查询结果字段", strGroups, Param.EditType.Default));
				alParam.add(new Param("Condition", ei.m_strCondition, "取值条件", "", strGroups, Param.EditType.SelectOrInput,strOptionalValues));
			}
//			for (int i = 0; i < m_alInputPort.size(); i++)//Port,连接时调用
//        	{
//        		VariablePort vp = (VariablePort)m_alInputPort.get(i);
//				alParam.add(new Param(vp.m_strVarName, String.format("%f", vp.m_dVarValue), vp.m_strVarName, "", "参数/变量", Param.EditType.Float));
//        	}
			
//			alParam.add(new Param("TagTableName", m_strTagTableName, "目标表", "目标表名", "目标文件", Param.EditType.Default));
//			alParam.add(new Param("TagTableTime", m_strTagTableTime, "目标表时间字段", "目标表时间字段", "目标文件", Param.EditType.Default));
//			alParam.add(new Param("ResultFilePath", m_strResultFilePath, "输出文件路径", "文本文件全路径", "目标文件", Param.EditType.File));
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		return alParam.size();
	}
	public boolean OnParamChanged(ArrayList<Param> alParam, int nIndex, Object objValue)
	{//当参数改变时
		if (alParam.get(nIndex).m_strName.equals("FilePath")) 
			{
			if(objValue.toString().contains("_HOR"))
				alParam.get(nIndex+1).m_objValue="小时";
			else  if(objValue.toString().contains("_DAY"))
				alParam.get(nIndex+1).m_objValue="日";
			else  if(objValue.toString().contains("_TEN"))
				alParam.get(nIndex+1).m_objValue="旬";
			else  if(objValue.toString().contains("_MON"))
				alParam.get(nIndex+1).m_objValue="月";
			else  if(objValue.toString().contains("_YER"))
				alParam.get(nIndex+1).m_objValue="年";
			return true;
			}
		if (alParam.get(nIndex).m_strName.equals("ExpressionItemCount"))
		{
			int i = 0, j = 0, nOldItemCount = Integer.parseInt((String)alParam.get(nIndex).m_objValue), nNewItemCount = Integer.parseInt(objValue.toString());
			if (nOldItemCount < nNewItemCount)
			{
				String strOptionalValues = "|字符|时间|降水|风向|X10|X100000|系统时间";
	        	
	        	j = nIndex + 1 + nOldItemCount * 3;
				for (i = nOldItemCount; i < nNewItemCount; i++)
				{
					String strGroups = String.format("取值条件/第%d个取值条件", i + 1);
					alParam.add(j++, new Param("OldTitle", "", "选择字段", "", strGroups, Param.EditType.Default));  
			        alParam.add(j++, new Param("NewTitle", "", "目标字段", "目标字段为要导入的目标表字段，如为空则默认设置为查询结果字段", strGroups, Param.EditType.Default));
					alParam.add(j++, new Param("Condition", "", "取值条件", "", strGroups, Param.EditType.SelectOrInput,strOptionalValues));
				}
			}
			else
			{
				j = nIndex + 1 + nNewItemCount * 3;
				for (i = nNewItemCount * 3; i < nOldItemCount * 3; i++)
					alParam.remove(j);
			}
			alParam.get(nIndex).m_objValue = objValue.toString();
			return true;
		}

		return super.OnParamChanged(alParam, nIndex, objValue);
	}
	//用于 XML->参数 等
	public int SetParam(final ArrayList<Param> alParam)
	{
		int i = super.SetParam(alParam);
		try
		{
//			m_strSourseTable= (String)alParam.get(i++).m_objValue;
//			m_strTimeType= (String)alParam.get(i++).m_objValue;
			final int nExpressionItemCount = Integer.parseInt((String)alParam.get(i++).m_objValue);
			m_alExpressionItem.clear();
			
			int j = 0, k = 0;
			ArrayList<String> alVar = new ArrayList<String>(); 
			Model2 model = (Model2)m_model;
			while (m_alExpressionItem.size() < nExpressionItemCount)
			{
				ExpressionItem ei = new ExpressionItem();
				ei.m_strOldTitle = (String)alParam.get(i++).m_objValue;
				ei.m_strNewTitle = (String)alParam.get(i++).m_objValue;
				ei.m_strCondition = (String)alParam.get(i++).m_objValue;
				if(ei.m_strNewTitle.equals(""))
					ei.m_strNewTitle=ei.m_strOldTitle;
				m_alExpressionItem.add(ei);
				
			}
			
//			i = alParam.size() - 3;
//			m_strTagTableName = (String)alParam.get(i++).m_objValue;
//			m_strTagTableTime = (String)alParam.get(i++).m_objValue;
//			m_strResultFilePath=(String)alParam.get(i++).m_objValue;
			
			//m_alOutputPort.get(0).SetName(m_strDatasetOutput + "@" + m_strDSOutput);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return i;	
	}
	
	public boolean Execute()
	{
		//1参数读入，约束条件判断
		Model2 model = ((Model2)m_model);
		int i = 0, j = 0;
		for (i = 0; i < m_alExpressionItem.size(); i++)
		{
			ExpressionItem ei = m_alExpressionItem.get(i);
			if (ei.m_strNewTitle.isEmpty())
			{
				model.OutputLog(Model.LogLevel.Error, String.format("\"%s-%d\"模块\"第%d个表达式\"参数为空。", GetName().replace("\n", ""), GetID(), i+1));
				return false;
			}		
		}
		ArrayList<String> oldTitleList=new ArrayList<String>();
		ArrayList<String> newTitleList=new ArrayList<String>();
		ArrayList<String> ConditionTitleList=new ArrayList<String>();
		for (int k = 0; k < m_alExpressionItem.size(); k++) 
		{
				oldTitleList.add(m_alExpressionItem.get(k).m_strOldTitle);
				newTitleList.add(m_alExpressionItem.get(k).m_strNewTitle);
				ConditionTitleList.add(m_alExpressionItem.get(k).m_strCondition);
		}
		List<String> dataReseltList=new ArrayList<String>() ;
		
		try {
			     Map<String, Integer> titleIndexMap=new HashMap<String, Integer>();
			     Map<String, String> typeMap=new HashMap<String, String>();
			     String[] tableTitleStrings=m_map.get(0).toString().split(",");
			     String[] tableTypeStrings=m_map.get(1).toString().split(",");
			     for(int in=0;in<tableTitleStrings.length;in++)
			     {
			    	 titleIndexMap.put(tableTitleStrings[in], in);
			    	 typeMap.put(tableTitleStrings[in], tableTypeStrings[in]);
			     }
			     
			     String titleString="";
             	String typeString="";
             	for (int k = 0; k < oldTitleList.size(); k++) {
                 	String oldtitleString=oldTitleList.get(k);
                 	titleString+=newTitleList.get(k);
                 	if (k != oldTitleList.size() - 1){
                 		titleString+=",";
     				}
                 	String oldType="";
                 	if(titleIndexMap.containsKey(oldtitleString))
                 	{
                 		oldType=typeMap.get(oldtitleString);
                 	}
                 	else if(oldtitleString.equals(""))
                 	{
                 		oldType="String";
					}
                 	
                 	if(ConditionTitleList.get(k).contains("时间"))
                 		oldType="Time";
                 	else if (ConditionTitleList.get(k).contains("char")) {
                 		oldType="String";
						}
                 	
                 	typeString+=oldType;
                 	if (k != oldTitleList.size() - 1){
                 		typeString+=",";
     				}
                 }
             	dataReseltList.add(titleString);
             	dataReseltList.add(typeString);

                for (int row = 2; row < m_map.size(); row++) {
                	String vvvvvString=(String)m_map.get(row);
                	String[] vlaueLiStrings=((String)m_map.get(row)).split(",",titleIndexMap.size());
 
                String valueString="";
                for (int k = 0; k < oldTitleList.size(); k++) {
                	String oldtitleString=oldTitleList.get(k);
                	
                	if(oldtitleString.trim().equals(""))
                	{
                		if(!ConditionTitleList.get(k).equals("时间")&&!ConditionTitleList.get(k).equals("降水")&&!ConditionTitleList.get(k).equals("风向")&&!ConditionTitleList.get(k).equals("X10")&&!ConditionTitleList.get(k).equals("X10")&&!ConditionTitleList.get(k).equals("X100000")&&!ConditionTitleList.get(k).equals("系统时间")&&!ConditionTitleList.get(k).equals("")&&!ConditionTitleList.get(k).equals("char3")&&!ConditionTitleList.get(k).equals("char4"))
                			{
                				valueString+=(""+ConditionTitleList.get(k)+"");
                				if (k != oldTitleList.size() - 1){
                					valueString+=",";
                				}
                				continue;
                			}
                		if(ConditionTitleList.get(k).equals("系统时间"))
                		{
                			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                			//System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
                			valueString+=df.format(new Date());//"to_date('"+df.format(new Date())+"','yyyy-MM-dd hh24:mi:ss')";
                			
                			if (k != oldTitleList.size() - 1){
            					valueString+=",";
            				}
                			continue;
                		}
                			
                	}
                	
                	String oldvalueString= "";
                	if(titleIndexMap.containsKey(oldTitleList.get(k)))
                	{
                		if(titleIndexMap.get(oldTitleList.get(k))==null)
                		{
                			return false;
                		}
                		String tempString=oldTitleList.get(k);
                		if(titleIndexMap.get(oldTitleList.get(k))>=vlaueLiStrings.length)
                		{
                			return false;
                		}
                		oldvalueString= vlaueLiStrings[titleIndexMap.get(oldTitleList.get(k))];
                	}
                	String newValuesString="";
                	//titleString+=newTitleList.get(k);
                	if(oldvalueString.equals("999999"))
                		newValuesString="";
                	else if(oldvalueString.equals("999998"))
                	{
                		newValuesString="32766";
					}
                	else if(oldvalueString.equals("999900"))
                	{
                		newValuesString="32700";
					}
                	else if(oldvalueString.equals(""))
                	{
                		newValuesString="";
					}
                	else
                	{
                		Double tempValue;
						if(ConditionTitleList.get(k).equals("时间"))
							{
							newValuesString=oldvalueString;//"to_date('"+oldvalueString+"','yyyy-MM-dd hh24:mi:ss')";
							}
						else if(ConditionTitleList.get(k).equals( "降水"))
						{
						 tempValue=Double.parseDouble(oldvalueString);
							if(tempValue>999800)
		                		newValuesString=(int)((tempValue-999800)*10+32000)+"";
		                	else if(tempValue>999700)
		                		newValuesString=(int)((tempValue-999800)*10+31000)+"";
		                	else if(tempValue>999600)
		                		newValuesString=(int)((tempValue-999800)*10+30000)+"";
		                	else
		                		newValuesString=(int)((tempValue)*10)+"";
						}
						else if(ConditionTitleList.get(k).equals( "风向"))
						{ 
							 tempValue=Double.parseDouble(oldvalueString);
							if(tempValue>999000)
		                		newValuesString=(int)((tempValue-999000)+32000)+"";
							else
		                		newValuesString=oldvalueString;
						}
						else if(ConditionTitleList.get(k).equals( "X10"))
						{ 
							tempValue=Double.parseDouble(oldvalueString);
		                		newValuesString=(int)((tempValue)*10)+"";
						}
						else if(ConditionTitleList.get(k).equals( "X100000"))
						{ 
							tempValue=Double.parseDouble(oldvalueString);
		                		newValuesString=(int)((tempValue)*100000)+"";
						}
						else if(ConditionTitleList.get(k).equals( ""))
						{ 
							newValuesString=oldvalueString;
						}
						
					}
                    if(ConditionTitleList.get(k).equals( "char3"))
					{ 
						if(oldvalueString.length()>3)
						{
	                		newValuesString="";
						}
						else 
						{
							newValuesString=oldvalueString;
						}
					}
					else if(ConditionTitleList.get(k).equals( "char4"))
					{ 
						if(oldvalueString.length()>4)
						{
	                		newValuesString="";
						}
						else 
						{
							newValuesString=oldvalueString;
						}
					}
                	valueString+=newValuesString;
    				if (k != oldTitleList.size() - 1){
    					valueString+=",";
    				}		
				}
                dataReseltList.add(valueString);
              }
                m_result=dataReseltList;
                model.OutputLog(Model.LogLevel.Error,m_result.toString());
    } catch (Exception e) {
    	model.OutputLog(Model.LogLevel.Error,"读取文件内容出错 "+e.getMessage());
        e.printStackTrace();
        return false;
    }
		OnParamChanged();
		return true;
	}
	public int GetOutputParam(Port port, ArrayList<Param> alParam)
	{
		int i = FindPort(port, false);
		if (i == -1)
			return 0;
		alParam.add(new Param("ResultString", m_result));
		return alParam.size();
	}
		
	class ExpressionItem
	{
		ExpressionItem()
		{
			m_strOldTitle = "";
			m_strNewTitle = "";
			m_strCondition = "";
		}
		
		String m_strOldTitle;
		String m_strNewTitle;
		String m_strCondition;
	}
	ArrayList<ExpressionItem> m_alExpressionItem;
	List<Object> m_map=null;
	List<String> m_result=null;
	
//	String m_strTimeType;
//	String m_strSourseTable;
//	String m_strTagTableName; 
//	String m_strTagTableTime;
//	String m_strResultFilePath;
//	String m_strResultFilePath_real;
}
